#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cstdarg>
#include <sys/types.h>
#include <unistd.h>

const std::string filename = "log/tcpserver.log";
//日志等级
enum
{
    Debug = 0,
    Info,
    Warning,
    Error,
    Fatal,
    Uknown
};

static std::string toLevelString(int level)
{
    switch(level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        return "Unknown";
    }
}

static std::string getTime()
{
    time_t curr = time(nullptr);
    struct tm* tmp = localtime(&curr);//将time_t时间戳转换成struct tm结构
    char buffer[128];
    snprintf(buffer,sizeof(buffer),"%d-%d-%d  %d:%d:%d",tmp->tm_year+1900,tmp->tm_mon+1,
            tmp->tm_mday,tmp->tm_hour,tmp->tm_min,tmp->tm_sec);

    return buffer;
}
//日志格式: 日志等级 时间 pid  消息体
//logMessage(Debug,"hello: %d, %s", 12, s.c_str()); //使用方式
void logMessage(int level,const char* format, ...)
{
    char logLeft[1024];//日志等级 时间 pid
    std::string level_string = toLevelString(level);//将等级转换成字符串
    std::string curr_time = getTime();//将时间转换成字符串
    snprintf(logLeft,sizeof(logLeft)," [%s] [%s] [%d] ", level_string.c_str(),curr_time.c_str(),getpid());

    char logRight[1024];
    va_list p;
    va_start(p,format);
    vsnprintf(logRight,sizeof(logRight),format,p);
    va_end(p);

    printf("%s %s\n", logLeft, logRight);

    //将打印日志保存到文件中
    // FILE* fp = fopen(filename.c_str(),"a");
    // if(fp == nullptr) return;

    // fprintf(fp,"%s %s\n",logLeft,logRight);
    // fflush(fp);
    // fclose(fp);
}
